package thread.synchronize;

/**
 * @author 真香
 * @create 2021-06-04 16:22
 */


import javax.print.attribute.standard.MediaSize;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 不安全的银行账户取钱
 *
 * 两个人去银行取钱
 *
 *
 */
public class UnsafeBank {

  public static void main(String[] args){
      Account account =new Account(100,"结婚基金");

      Drawing you = new Drawing(account,50,"你");
      Drawing grilFriends = new Drawing(account,50,"女朋友");
      you.start();
      grilFriends.start();
      Lock lock = new ReentrantLock();
  }

}



// 账户
class Account{

    // 余额
    int money;

    // 卡号
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}



// 银行:模拟取款
class Drawing extends Thread {

    private Account account;


    // 取了多少钱
    int drawingMoney;

    // 现在手里多少钱
    int nowMoney;

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;

    }


    // 取钱

    /**
     *  synchronized 默认锁是对象当前类= this
     *   但是在synchronized使用在代码块时推荐使用共享资源，必须这里
     *   共享资源是对account 账户的操作，那就用它做锁
     */

    @Override
    public   void run() {
        synchronized (account) {
            //判断账户余额是否足够本次取钱
            if (account.money - drawingMoney < 0) {
                System.out.println("账户余额不足.......");
                return;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


                // 银行账户的钱=  现有钱- 取出的钱
                account.money = account.money - drawingMoney;
                // 手里的钱 = 手里的钱 + 取出的钱
                nowMoney = nowMoney + drawingMoney;
        }
        System.out.println(account.name+"余额为:"+account.money);
        // this.getName()== Thread.currentThread().getName() 因为Drawing 继承了Thread 所以是子类 this代表Thread
        System.out.println(this.getName()+"手里的钱为:"+nowMoney);



    }
}

